package com.acme.bankapp.service.bank;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.acme.bankapp.domain.bank.Account;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.BankException;
import com.acme.bankapp.domain.bank.NotEnoughFundsException;
import com.acme.bankapp.domain.bank.OverDraftLimitExceededException;

public class BankApplication {

	public static void main(String[] args) {
		try {
			Bank bank = BankService.createBankWithListeners();
			BankService.generateClients(bank, 7);
			BankService.printMaximumAmountToWithdraw(bank);
			try {
				BankService.modifyBank(bank);
			} catch (BankException e) {
				if (e instanceof OverDraftLimitExceededException) {
					System.out.println("Overdraft limit exceeded exception");
					OverDraftLimitExceededException o = (OverDraftLimitExceededException) e;
					System.out.println("Maximum amount to withdraw: "
							+ o.getMaximumAmountToWithdraw());
					System.out.println("Trying to withdraw: "
							+ (o.getMaximumAmountToWithdraw() + o.getAmount()));
					System.out.println("Limit exceeded by: " + o.getAmount());
				} else if (e instanceof NotEnoughFundsException) {
					System.out.println("Not enough funds exception");
				}
			}
			BankService.printMaximumAmountToWithdraw(bank);
			BankService.printClients(bank);
			
			if ((args.length == 1) && (args[0].equals("-statistics"))) {
				InputStreamReader systemReader = new InputStreamReader(System.in);
				BufferedReader consoleReader = new BufferedReader(systemReader);
				boolean interactive = true;
				while (interactive) {
					String command = consoleReader.readLine();
					if (command.equals("exit")) {
						interactive = false;
					} else if (command.equals("getNbOfCustomers")) {
						System.out.println(BankReport.getNbOfCustomers(bank));
					} else if (command.equals("getNbOfAccounts")) {
						System.out.println(BankReport.getNbOfAccounts(bank));
					} else if (command.equals("getBankCredit")) {
						System.out.println(BankReport.getBankCredit(bank));
					} else if (command.equals("getAccountsSortedBySum")) {
						for (Account account: BankReport.getAccountsSortedBySum(bank)) {
							System.out.println(account);
						}
					} else if (command.equals("getCustomerAccount")) {
						System.out.println(BankReport.getCustomerAccount(bank));
					} else {
						System.out.println("Unknown command");
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
